package gormx

import (
	"fmt"
	"log"
	"os"

	"gitee.com/yanwc/gozero-utils/fileconfig"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func NewGorm(c fileconfig.MySql, logger logger.Interface, opts ...gorm.Option) *gorm.DB {
	opts = append(opts, &gorm.Config{AllowGlobalUpdate: false, Logger: logger})
	db, err := gorm.Open(mysql.Open(DSN(c)), opts...)
	if err != nil {
		panic(err)
	}

	return db
}

func NewGormLogger(cfg logger.Config) logger.Interface {
	return logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		cfg,
	)
}

func DSN(c fileconfig.MySql) string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.User,
		c.Pwd,
		c.Host,
		c.Port,
		c.Db)
}
